package cn.edu.zafu.bigdata.rwx.web;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPClockClient {
    private DatagramSocket socket;
    private InetAddress address;

    public UDPClockClient(String ip, int port) throws Exception {
        socket = new DatagramSocket();
        address = InetAddress.getByName(ip);
    }

    public void requestTime() throws Exception {
        byte[] buf = new byte[256];
        // 发送请求到服务器
        String request = "请求当前时间";
        buf = request.getBytes();
        DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 12345);
        socket.send(packet);

        // 接收服务器响应
        packet = new DatagramPacket(buf, buf.length);
        socket.receive(packet);

        // 打印服务器时间
        String serverTime = new String(packet.getData(), 0, packet.getLength());
        System.out.println("服务器时间：" + serverTime);
    }

    public void closeSocket() {
        socket.close();
    }

    public static void main(String[] args) {
        String serverIp = "127.0.0.1";
        int serverPort = 12345;
        try {
            UDPClockClient client = new UDPClockClient(serverIp, serverPort);
            client.requestTime();
            client.closeSocket();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
